class DatePlus extends Date {
  constructor(args) {
    args ? super(args) : super();
  }
  Format(fmt = 'yyyy-MM-dd hh:mm:ss') {
    const quarterlyMonths = 3;
    const o = {
      //月份
      'M+': this.getMonth() + 1,
      'd+': this.getDate(),
      'h+': this.getHours(),
      'm+': this.getMinutes(),
      's+': this.getSeconds(),
      'q+': Math.floor((this.getMonth() + quarterlyMonths) / quarterlyMonths),
      S: this.getMilliseconds(),
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        `${this.getFullYear()}`.substr(quarterlyMonths + 1 - RegExp.$1.length)
      );
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
        );
      }
    }
    return fmt;
  }
}

function _typeof(obj) {
  if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
    _typeof = function (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function (obj) {
      return obj &&
        typeof Symbol === 'function' &&
        obj.constructor === Symbol &&
        obj !== Symbol.prototype
        ? 'symbol'
        : typeof obj;
    };
  }

  return _typeof(obj);
}

/**
 * @description: 对象深拷贝
 * @param {Object} obj
 * @return {Object}
 */
function deepCopy(obj) {
  const result = Array.isArray(obj) ? [] : {};

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (_typeof(obj[key]) === 'object') {
        result[key] = deepCopy(obj[key]);
      } else {
        result[key] = obj[key];
      }
    }
  }

  return result;
}

/**
 * @desc   判断安卓系统版本号
 * @return {String} 如4.3.2或者9.0
 */
function getGphoneVersion() {
  const ua = navigator.userAgent.toLowerCase();
  let version = null;

  if (ua.indexOf('android') > 0) {
    const reg = /android [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @desc   判断苹果系统版本号
 * @return {String} 如9.3.2或者9.0
 */
function getIphoneVersion() {
  const ua = navigator.userAgent.toLowerCase();
  let version = null;

  if (ua.indexOf('like mac os x') > 0) {
    const reg = /os [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @description: 获取系统信息
 * @return {Object} sys: 手机系统    version: 系统版本号
 */
function getOS() {
  const SYS = /(iphone)|(mac)|(ipad)/gi.test(navigator.userAgent) ? 'iphone' : 'gphone';
  return {
    sys: SYS,
    version: SYS === 'iphone' ? getIphoneVersion() : getGphoneVersion(),
  };
}

/**
 * @description: 设置页面标题
 * @param {String} str
 */
function setTitle(str) {
  document.title = str;

  if (/hexin/gi.test(navigator.userAgent)) {
    if (navigator.userAgent.toLowerCase().indexOf('android') > 0) {
      window.callNativeHandler('changeWebViewTitle', {
        title: str,
        url: '',
      });
    } else {
      window.callNativeHandler('updateTitleAutomatically');
    }
  }
}

/**
 * @description: 安卓单页应用调用协议解决页面返回 bug
 */
function androidCanBackProtocol() {
  if (/hexin/gi.test(navigator.userAgent) && getOS().sys === 'gphone') {
    const data = {
      method: 'setBrowserField',
      params: {
        isUseDefaultBack: 'true',
      },
    };
    window.callNativeHandler('notifyWebHandleEvent', JSON.stringify(data));
  }
}

/**
 * @description: 动态加载 js 脚本文件
 * @param {String} url
 * @param {Function} nextFn
 */
function loadJs(url, nextFn) {
  const body = document.getElementsByTagName('body')[0];
  const jsNode = document.createElement('script');
  jsNode.setAttribute('type', 'text/javascript');
  jsNode.setAttribute('src', url);
  body.appendChild(jsNode);

  if (document.all) {
    //如果是IE
    jsNode.onreadystatechange = function () {
      if (jsNode.readyState === 'loaded' || jsNode.readyState === 'complete') {
        nextFn && nextFn();
      }
    };
  } else {
    jsNode.onload = function () {
      nextFn && nextFn();
    };
  }
}

/**
 * @description: 验证登录（包含微信授权登录）
 * @param {Function} nextFn
 * 依赖loadJs
 */
function checkLogin(nextFn) {
  if (window.getAppVersion()) {
    if (window.getAccount()) {
      typeof nextFn === 'function' && nextFn();
    } else {
      window.location.href = 'http://eqhexin/changeUser';
    }
  } else {
    if (window.getUserid()) {
      typeof nextFn === 'function' && nextFn();
    } else {
      if (window.wechatLogin) {
        window.wechatLogin(encodeURIComponent(window.location.href));
      } else {
        loadJs('https://upass.10jqka.com.cn/asset/wechatlogin/js/checkwechat.js', function () {
          window.wechatLogin(encodeURIComponent(window.location.href));
        });
      }
    }
  }
}

/**
 * 跳转客户端股票分时页
 * @param {string | number} stockCode 股票代码
 * @param {string | number} marketId 市场id
 */
function jumpToFenShi(stockCode, marketId) {
  location.href = `client://client.html?action=ymtz^webid=2205^stockcode=${stockCode}^marketid=${marketId}`;
}

//消抖
function debounce(fn, delay) {
  let timer = null;
  return function () {
    const args = arguments;
    const context = this;
    if (timer) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    } else {
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    }
  };
}
/**
 * 调用 2804 webview 打开新页面
 * @param {string} url 跳转地址
 */
function jumpBy2804(url) {
  if (!url || typeof url !== 'string') {
    return;
  }
  if (window.getAppVersion() && url.indexOf('client.html') === -1) {
    !url.startsWith('http') && (url = location.protocol + url);
    location.href = `client://client.html?action=ymtz^webid=2804^mode=new^url=${url}`;
  } else {
    location.href = url;
  }
}

// 错误上报
const errorReport = ({ name, message, stack, category = 'ajax' }) => {
  window.ClientMonitor.reportFrameErrors(
    {
      // 类型
      category,
      // 级别
      grade: 'Error',
    },
    {
      name,
      message,
      stack,
    }
  );
};

// 获取动态域名
function getUrlByPromise(configUrl) {
  return new Promise(resolve => {
    window.dynamicDomain.exchangeHost(configUrl, function (url) {
      resolve(url);
    });
  });
}

class LocalStorageManager {
  constructor(storageKey, featureKey) {
    this.storageKey = storageKey;
    this.featureKey = featureKey;
    if (!this.isLocalStorageSupported()) {
      errorReport({
        name:'不支持localstorage',
        message:'',
        stack:'localstorage不可用'
      });
    } else {
      this.init(storageKey, featureKey);
    }
  }

  init(storageKey, featureKey) {
    if (!window.localStorage.getItem(storageKey)) {
      window.localStorage.setItem(storageKey, JSON.stringify({ [featureKey]: {} }));
    } else {
      const data = this.getData();
      if (!data[featureKey]) {
        data[featureKey] = {};
        window.localStorage.setItem(storageKey, JSON.stringify(data));
      }
    }
  }

  getData() {
    try {
      const data = window.localStorage.getItem(this.storageKey);
      return data ? JSON.parse(data) : {};
    } catch (error) {
      errorReport({
        name:`localstorage中getData异常-${error.name}`,
        message:error.message,
        stack:error.stack
      });
      return {};
    }
  }

  isLocalStorageSupported() {
    try {
      const testKey = '__test__';
      window.localStorage.setItem(testKey, testKey);
      window.localStorage.removeItem(testKey);
      return true;
    } catch (error) {
      errorReport({
        name:`localstorage中isLocalStorageSupported异常-${error.name}`,
        message:error.message,
        stack:error.stack
      });
      return false;
    }
  }
  setValue(obj, keys, value) {
    // 将字符串键拆分成数组
    const keyArray = (keys + '').split('.');

    // 获取要修改的对象引用
    let target = obj;
    for (let i = 0; i < keyArray.length - 1; i++) {
      const key = keyArray[i];
      // 如果属性不存在，创建一个空对象
      if (!target[key]) {
        target[key] = {};
      }
      // 更新目标对象引用
      target = target[key];
    }
    // 设置属性值
    target[keyArray[keyArray.length - 1]] = value;

    return obj;
  }

  getItem(key, defaultValue = null) {
    try {
      const keyArr = (key + '').split('.');
      const data = this.getData();
      let result = void 0;
      keyArr.forEach((item, index) => {
        if (!index) {
          result = data[this.featureKey]?.[item];
        } else {
          result = result?.[item];
        }
      });
      return result || defaultValue;
    } catch (error) {
      errorReport({
        name:`localstorage中getItem异常-${error.name}`,
        message:error.message,
        stack:error.stack
      });
      return defaultValue;
    }
  }

  setItem(key, value) {
    try {
      const data = this.getData();
      this.setValue(data[this.featureKey], key, value);
      window.localStorage.setItem(this.storageKey, JSON.stringify(data));
    } catch (error) {
      errorReport({
        name:`localstorage中setItem异常-${error.name}`,
        message:error.message,
        stack:error.stack
      });
    }
  }

  removeItem(key) {
    try {
      const data = this.getData();
      delete data[this.featureKey][key];
      window.localStorage.setItem(this.storageKey, JSON.stringify(data));
    } catch (error) {
      errorReport({
        name:`localstorage中removeItem异常-${error.name}`,
        message:error.message,
        stack:error.stack
      });
    }
  }
}

const setTitlebar = (textContent, callback) => {
  window.callNativeHandler(
    'notifyWebHandleEvent',
    {
      method: 'setTitleBar',
      params: {
        rightViewType: 'TextFunctionView',
        stopSetNil: 'yes',
        textContent: textContent,
        buttonName: 'submitBtn',
      },
    },
    () => {
      // 协议
    }
  );
  window.callNativeHandler('changeWebViewButton', '');
  window.registerWebHandler('changeWebViewButton', () => {
    callback();
  });
};

function getMidnightTimestamp(date) {
  // 将传入的日期对象转换为当地时间
  const localDate = new Date(date);
  // 设置时间为当天的0点
  localDate.setHours(0, 0, 0, 0);
  // 获取当天0点的时间戳并返回
  return localDate.getTime();
}

export default {
  DatePlus,
  deepCopy,
  getOS,
  setTitle,
  androidCanBackProtocol,
  checkLogin,
  jumpToFenShi,
  jumpBy2804,
  debounce,
  errorReport,
  getUrlByPromise,
  LocalStorageManager,
  setTitlebar,
  getMidnightTimestamp,
};
